(function($) {
	var sourceData;
	var currPath=[];
	var perInfo=""
	$.init();
	$.plusReady(function() {
		baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}

	function getFilePathData(){
		mui('.itemArea').each(function (index,element) {
			element.removeEventListener('tap',itemTapped)
			if (this.querySelector('.photo')) {
				this.querySelector('.itemImg').removeEventListener('tap',imgItemTapped)
				this.querySelector('.itemText').removeEventListener('tap',imgItemTapped)
				this.querySelector('.itemDate').removeEventListener('tap',imgItemTapped)
			}
		})
		mui('.itemArea .photo').each(function (index,element) {
			element.removeEventListener('error',photoLoadError)
		})
		var par='0'
		if (currPath.length > 0) {
			var lastPathDom = $('#path')[0].lastChild
			par = lastPathDom.getAttribute('data-pid')
		}
		var pdict = {'par':par,'dateFlag':'0','appFlag':'1','nurseid':perInfo['loginID'],'input':$('#search')[0].value} //
		var paramDict = {'method':'web.INMOrgComm:FindFileTree2','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		console.log(JSON.stringify(pdict))
		$("#scroll")[0].innerHTML = ''
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				showNullTip(result.msg)
				return
			}
			var dataArr = result.data
			sourceData = dataArr;
			updateUI()
		}, function(errorStr) {
			sourceData = [];
			$("#scroll")[0].innerHTML = ''
			showNullTip(errorStr)
		});
	}

	function updateUI(){
		$('#wrapper').scroll().scrollTo(0,0,100);
		var scroll = $("#scroll")[0];
		if (!sourceData || sourceData.length==0) {
			showNullTip("暂无数据")
			scroll.innerHTML = ''
			return
		}
		var htmls = ''
		for(var i = 0; i < sourceData.length; i++){
			var oneData = sourceData[i]
			var icon='word'
			var iconStr=''
			if (oneData['type'] == 'D') {
				iconStr = '<div class="itemImg"><img src="../dependence/teach/images/file_folder.svg"/></div>';
			}else{
				var oneUrl = oneData['url']
				icon = fileTypeIcon(oneData['ext']);
				iconStr = '<div class="itemImg"><img src="../dependence/teach/images/'+icon+'.svg"/></div>';
				if (icon == 'img') {
					iconStr += '<div class="itemImg"><img class="photo" src="'+
						perInfo.TomcatUrl+'/'+oneUrl +'" data-preview-group="'+currPath.length+'" data-preview-src="" /></div>';
				}
			}
			var html = iconStr+'<div class="itemText">'+oneData['label']+'</div>'+
				'<div class="itemDate">'+oneData['createDate']+'</div>';
			htmls += '<div class="itemArea" id="file-'+i+'">'+html+'</div>'
		}
		scroll.innerHTML = htmls
		hideNullTip()
		mui('.itemArea').each(function (index,element) {
			if (this.querySelector('.photo')) {
				this.querySelector('.itemImg').addEventListener('tap',imgItemTapped)
				this.querySelector('.itemText').addEventListener('tap',imgItemTapped)
				this.querySelector('.itemDate').addEventListener('tap',imgItemTapped)
				return
			}
			element.addEventListener('tap',itemTapped)
		})
		mui.previewImage();
		mui('.itemArea .photo').each(function (index,element) {
			element.addEventListener('error',photoLoadError)
		})
	}
	function imgItemTapped(){
		var dom = this.parentNode.querySelector('.photo')
		if (dom.getAttribute('data-exist')!= "No") {
			mui.trigger(dom,'tap')
		}else{
			mui.toast('图片不存在')
		}
	}
	function itemTapped(){
		var idStr = this.id;
		var index = parseInt(idStr.split('-')[1]);
		var data = sourceData[index]
		if (data['type'] == 'D') {
			appendFilePath(data);
			getFilePathData();
			return;
		}
		url = perInfo.TomcatUrl +'/'+data.url
		
		var fileType = fileTypeIcon(data['ext'])
		if (fileType == 'img') {
			return;
		}
		var label = this.querySelector('.itemText').innerText
		var pageName = ''
		switch (fileType){
			case "pdf":
			case "word":
			case "ppt":
				pageName = '../FilePreview/pdfReader.html'
				break;
			case "txt":
				pageName = 'filePreview.html'
				break;
			default:
				break;
		}
		if (pageName == '') {
			mui.toast('暂不支持此类型文件')
			return
		}
		mui.checkUrlReal(url,function(){
			var webview = plus.webview.create(pageName, pageName, {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'title':label,'fileUrl':url});
			webview.show('fade-in');
		},function(){
			mui.toast('文件不存在')
		})
		
	}
	function photoLoadError(){
		this.setAttribute('data-exist',"No")
	}
	//<div class="pathText">内科护理</div><div class="mui-icon mui-icon-arrowright"></div>
	function appendFilePath(dict){
		document.body.classList.remove('home');
		var pathDom = $('#path')[0]
		if (currPath.length > 0) {
			var arrowright = document.createElement('div');
			arrowright.setAttribute('class','arrowright');
			arrowright.innerHTML = '<img src="../dependence/teach/images/arrowR.svg" />'
			pathDom.appendChild(arrowright);
		}
		var pathText = document.createElement('div');
		pathDom.appendChild(pathText);
		pathText.classList.add('pathText');
		pathText.innerText = dict.label;
		pathText.setAttribute('data-pid',dict['id']);
		pathText.id='path-'+currPath.length;
		pathText.addEventListener('tap',changePath)
		currPath.push(dict.label)
		var pathWrapper = $('#pathWrapper')[0];
		var maxScrollX = pathWrapper.clientWidth - $('#path')[0].clientWidth;
		if (maxScrollX >= 0) {			
			return;
		}
		mui('#pathWrapper').scroll().scrollTo(maxScrollX,0,100);
		mui('#pathWrapper').scroll().reLayout();
	}
	function changePath(){
		var index = parseInt(this.id.split('-')[1])
		if (index == currPath.length-1) { //点击的最后一个,回到顶部
			$('#wrapper').scroll().scrollTo(0,0,100);
			return;
		}
		removeFilePath(index);
		getFilePathData();
	}
	function removeFilePath(index){
		var pathDom = $('#path')[0]
		for (var i = currPath.length - 1; i > index;i--) {
			var pathText = $('#path-'+i)[0];
			pathText.removeEventListener('tap',changePath)
			if (pathText) {
				var pre = pathText.previousElementSibling ;
				pathDom.removeChild(pathText)
				if (pre) {
					pathDom.removeChild(pre)
				}
			}
			currPath.splice(i);
		}
		var pathWrapper = $('#pathWrapper')[0];
		var maxScrollX = pathWrapper.clientWidth - $('#path')[0].clientWidth;
		if (maxScrollX >= 0) {			
			maxScrollX = 0
		}
		mui('#pathWrapper').scroll().scrollTo(maxScrollX,0,100);
	}
	
	function baseSetup() {
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		perInfo = app.getState()
		$.back = backBtnTapped;
		mui('header').on('tap','#backBtn',backBtnTapped)
		$('.mui-bar').on('tap', '#listBtn', function() {
			var wrapperDom = $('#wrapper')[0];
			var img = this.querySelector('img')
			if (wrapperDom.getAttribute('class').indexOf('folderType') != -1) {
				this.classList.add('mui-active')
				wrapperDom.classList.remove('folderType')
				setTimeout(function() {
					img.src="../dependence/teach/images/file_list.svg"
				}, 200);
			} else {
				this.classList.remove('mui-active')
				wrapperDom.classList.add('folderType')
				setTimeout(function() {
					img.src="../dependence/teach/images/file_block.svg"
				}, 200);
			}
		});
		$('.mui-bar').on('tap', '#orderBtn', function() {
			sourceData.reverse()
			if (this.getAttribute('class').indexOf('mui-active') != -1) {
				this.classList.remove('mui-active')
			} else {
				this.classList.add('mui-active')
			}
			updateUI();
		});
		mui("body").on("tap", ".searchArea .mui-icon-clear", function() {
			if ($('#search')[0] != "") {
				$('#search')[0].value = ""
			}
			getFilePathData();
		});
		var search = document.getElementById('search');
		search.addEventListener('input',function(){
			getFilePathData();
		});
		//home图标点击
		mui(".pathArea").on("tap", ".mui-icon-home-filled", function() {
			mui('#path .pathText').each(function (index,element) {
				element.removeEventListener('tap',changePath)
			})
			currPath = [];
			$('#path')[0].innerHTML = ''
			document.body.classList.add('home');
			getFilePathData();
		});
		getFilePathData()
	}
	function fileTypeIcon(url){
		var icon = ''
		url = url.toLowerCase()
		if (url=='pdf') {
			icon = 'pdf'
		}else if (url=="png"||url=="jpg"||url=="jpeg"||url=="gif"||url=="bmp") {
			icon = 'img'
		}else if (url=="doc"|| url=="docx") {
			icon = 'word'
		}else if (url=="ppt"|| url=="pptx") {
			icon = 'ppt'
		}else if (url == "txt" || url == "json") {
			icon = 'txt'
		}else{
			icon = 'file'
		}
		return icon
	}
	function showNullTip(msg){
		mui('.nullData')[0].style.display = 'block';
		mui('.nullTip')[0].innerHTML = msg
	}
	
	function hideNullTip(){
		mui('.nullData')[0].style.display = 'none';
	}
	function backBtnTapped(){
		var pathDom = $('#path .pathText')
		var count = pathDom.length
		if (count == 0) {
			plus.webview.currentWebview().close()
			return
		}else if (count == 1) {
			mui.trigger($('.mui-icon-home-filled')[0],'tap')
			return
		}else{
			mui.trigger(pathDom[count - 2],'tap')
			return
		}
	}
})(mui);
